package com.hmkj.web.controller;

import com.google.code.kaptcha.Producer;
import com.hmkj.boot.config.CaptchaHelper;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.core.constant.SessionId;
import com.xiaoleilu.hutool.lang.Base64;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.ApplicationContext;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;

@Api(description = "图片验证码相关")
@RestController
@RequestMapping(value = GenericController.BASE_API_URL + "/captcha")
public class CaptchaController extends GenericController {

    @ApiOperation(value = "获取图片验证码", notes = "获取图片验证码")
    @RequestMapping(value = "getcaptcha", method = RequestMethod.GET)
    public ResultEntity getCaptcha() throws Exception {
//        String str = new CaptchaHelper().createCaptcha();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        Producer captchaProducer = (Producer) context.getBean("captchaProducer");
        String capText = captchaProducer.createText();

        BufferedImage bi = captchaProducer.createImage(capText);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", out);
        String image = "data:image/jpg;base64," + Base64.encode(out.toByteArray());

        try {
            out.flush();
        } finally {
            out.close();
        }
        setSession(SessionId.CAPTCHA, capText);
        return ok(image);
    }


    @ApiOperation(value = "校验图片验证码", notes = "校验图片验证码")
    @RequestMapping(value = "check", method = RequestMethod.GET)
    public ResultEntity check(@RequestParam(value = "captcha") String captcha) throws Exception {
        if (checkCaptcha(captcha)) {
            return ok();
        } else {
            return fail("验证码错误");
        }
    }
}
